<template>
  <div class="scheduling">
    <!-- 查询条件 -->
    <el-form :inline="true" :model="elform" :rules="elRule" size="mini" ref="elform">
      <el-form-item label="姓名" prop="userGuid">
        <el-select
          v-model="elform.userGuid"
          placeholder="请选择"
          style="width:120px"
          filterable
          clearable
          size="mini"
          @change="hanleDate"
        >
          <el-option
            v-for="item in userOption"
            :key="item.userGuid"
            :label="item.userName"
            :value="item.userGuid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-date-picker
          v-model="timeValue"
          type="month"
          placeholder="选择月"
          :clearable="false"
          @change="hanleDate"
          style="width:110px"
          :disabled="elform.userGuid == ''"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="考勤班次" prop="attendanceRuleGuid">
        <el-select
          v-model="elform.attendanceRuleItem"
          placeholder="请选择"
          filterable
          clearable
          style="width:100%"
          size="mini"
        >
          <el-option
            v-for="item in attendanceRuleOption"
            :key="item.ruleFrameGuid"
            :label="item.ruleFrameName"
            :value="item.ruleFrameGuid+','+item.ruleFrameName+','+item.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="应用范围">
        <el-select
          v-model="elform.application"
          placeholder="请选择"
          style="width:150px"
          filterable
          clearable
          size="mini"
          @change="handleDateRange"
        >
          <el-option
            v-for="item in applicationOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onQueryt" size="mini">查询</el-button>
        <!-- <el-button type="primary" @click="setupWork" size="mini">将工作日全部设置上所选时段</el-button> -->
        <el-button type="primary" @click="onSubmit" size="mini">保存排班内容</el-button>
      </el-form-item>
    </el-form>
    <div class="building_romm_list1">
      <div class="shebeiColor frame"></div>
      <span>角色排班</span>
      <div class="shebeiColor rule"></div>
      <span>个人排班</span>
    </div>
    <!-- 上一月和下一月 -->
    <div class="nextRre">
      <button
        ref="prevBtn"
        class="el-button el-button--default el-button--medium"
        style="padding:5px 20px;"
      >上一月</button>
      <button
        ref="nextBtn"
        class="el-button el-button--default el-button--medium"
        style="padding:5px 20px;"
      >下一月</button>
    </div>
    <!-- 日历显示 -->
    <el-calendar v-model="timeValue">
      <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
      <template slot="dateCell" slot-scope="{date, data}">
        <!-- :class="[{ 'rule': dealMyDate(data.day).type == 'rule' },{ 'frame': dealMyDate(data.day).type == 'frame' }]" -->
        <p @click="handle" :class="[{ 'isShow': dealMyDate(data.day).ruleType == 1},{ 'rule': dealMyDate(data.day).ruleType == 2}]">
          <!--这里原本有动态绑定的class，去掉-->
          {{ data.day.split('-')[2] }}
          <!-- {{ data.day.split('-').slice(1).join('-') }} -->
          <br />
          {{ dealMyDate(data.day) | getContent}}
        </p>
      </template>
    </el-calendar>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
export default {
  data() {
    return {
      /**
       * 日期处理
       */
      // 全部日期
      dayDate: [],
      // 工作日期
      workingDate: [],
      // 周六
      saturdayDate: [],
      // 周日
      weekendDate: [],
      /**
       * 查询条件
       */
      // 月份
      monthTime: new Date(),
      // 用户
      userOption: [],
      // 考勤班次
      attendanceRuleOption: [
        {
          ruleFrameName: '不排班',
          ruleFrameGuid: 'no',
          type: 'no'
        }
      ],
      // 班次应用范围
      applicationOption: [
        {
          value: 4,
          label: '应用于所有日期'
        },
        {
          value: 1,
          label: '应用于所有工作日'
        },
        {
          value: 2,
          label: '应用于周六'
        },
        {
          value: 3,
          label: '应用于周日'
        }
      ],
      elform: {
        userGuid: '',
        endDate: '',
        startDate: '',
        attendanceRuleItem: ''
      },
      elRule: {
        // roleGuidList: [
        //   {
        //     required: true,
        //     message: ' ',
        //     trigger: 'blur'
        //   }
        // ]
      },
      /** 日历 */
      // 数据
      timeValue: new Date(),
      // 被选中的数据
      resDate: [],
      //   用户已经绑定日期
      roleData: []
    }
  },
  created() {
    this.changeschoolid = this.$store.state.user.changeschoolid
    // 获取用户
    this.getRole()
    // 获取考勤班次
    this.getRule()
    // 初始化全部时间，和工作时间
    this.getDaysInMonth(this.timeValue)

    this.$nextTick(() => {
      let prevBtn = this.$refs.prevBtn
      let nextBtn = this.$refs.nextBtn
      let btn = document.querySelector('.el-calendar__button-group')
      btn.appendChild(prevBtn)
      btn.appendChild(nextBtn)
      // 点击前一个月
      prevBtn.addEventListener('click', e => {
        console.log(this.elform)
        if (typeof this.timeValue != 'string') {
          this.timeValue = this.formatDate(
            this.timeValue,
            'yyyy-MM-dd hh:mm:ss'
          )
        }
        let d = this.timeValue.split('-')
        let time = new Date(d[0], d[1] - 1, 0, 0, 0, 0, 0)
        let resDate = this.formatDate(time, 'yyyy-MM-dd hh:mm:ss')
        this.$confirm('此操作将不会保存您之前的操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.timeValue = resDate
            // 初始化日期，和查询数据
            this.hanleDate()
          })
          .catch(() => {})
      })
      //点击下一个月
      nextBtn.addEventListener('click', e => {
        if (typeof this.timeValue != 'string') {
          this.timeValue = this.formatDate(
            this.timeValue,
            'yyyy-MM-dd hh:mm:ss'
          )
        }
        let d = this.timeValue.split('-')
        let time = new Date(d[0], Number(d[1]) + 1, 0, 0, 0, 0, 0)
        let resDate = this.formatDate(time, 'yyyy-MM-dd hh:mm:ss')
        this.$confirm('此操作将不会保存您之前的操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.timeValue = resDate
            // 初始化日期，和查询数据
            this.hanleDate()
          })
          .catch(() => {})
      })
    })
  },
  filters: {
    getContent(val) {
      let type =
        val.type == 'rule' ? 'attendanceRuleName' : 'attendanceFrameName'
      let arr = val
      let res = arr[type]
      return res
    }
  },
  methods: {
    // 应用范围
    handleDateRange(val) {
      if (val == 4) {
        this.setupWork(this.dayDate)
      } else if (val == 1) {
        this.setupWork(this.workingDate)
      } else if (val == 2) {
        this.setupWork(this.saturdayDate)
      } else if (val == 3) {
        this.setupWork(this.weekendDate)
      } else {
      }
    },
    setupWork(allDate) {
      if (
        this.elform.attendanceRuleItem == '' ||
        this.elform.attendanceRuleItem == null
      ) {
        this.$message.error('请选择考勤班次后再进行操作')
        return false
      }
      // this.resDate = [];
      let week = []
      const {
        ruleFrameGuid,
        ruleFrameName,
        type,
        ruleguid_type,
        rulename_type
      } = this.getAttendance()
      let arr = this.resDate.filter(
        item => !allDate.includes(item.attendanceDate)
      )
      if (ruleFrameGuid != 'no') {
        allDate.map(item => {
          week.push({
            attendanceDate: this.formatDate(
              new Date(item + ' 00:00:00'),
              'yyyy-MM-dd'
            ),
            [ruleguid_type]: ruleFrameGuid,
            [rulename_type]: ruleFrameName,
            type
          })
        })
      }
      this.resDate = [...arr, ...week]
    },
    /**
     * 日期处理
     */

    //根据某年某月计算出所有具体日期，并标注是礼拜几
    getDaysInMonth(time) {
      // 全部日期
      this.dayDate = []
      // 工作日期
      this.workingDate = []
      if (typeof time != 'string') {
        time = this.formatDate(time, 'yyyy-MM-dd hh:mm:ss')
      }
      let d = time.split('-')
      const daysOfMonth = []
      let year = d[0]
      let month = d[1]
      month = parseInt(month, 10)
      const lastDayOfMonth = new Date(year, month, 0).getDate()
      month = (month + '').padStart(2, '0')
      for (let i = 1; i <= lastDayOfMonth; i++) {
        let day = (i + '').padStart(2, '0')
        let date = year + '-' + month + '-' + day
        let time = date + ' 00:00:00'
        let week = new Date(time).getDay()
        if (week != 0 && week < 6) {
          this.workingDate.push(date)
        } else if (week == 0) {
          this.weekendDate.push(date)
        } else if (week == 6) {
          this.saturdayDate.push(date)
        }
        this.dayDate.push(date)
        daysOfMonth.push({ date, week })
      }
      console.log(this.dayDate)
      console.log(this.workingDate)
      console.log(this.weekendDate)
      console.log(this.saturdayDate)
      console.log(daysOfMonth)
      return daysOfMonth
    },
    // 当日期变化时,初始化信息
    hanleDate() {
      this.getDaysInMonth(this.timeValue)
      this.onQueryt()
    },

    /**
     * 条件获取
     */
    // 获取用户
    getRole() {
      this.$http({
        url: this.$http.adornUrl('/api/v1/Student/user-department-brief-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.userOption = data.messageContent || []
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 获取考勤班次
    getRule() {
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-rule-and-frame'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.attendanceRuleOption = [
            {
              ruleFrameName: '不排班',
              ruleFrameGuid: 'no',
              type: 'no'
            },
            ...data.messageContent
          ] || [
            {
              ruleFrameName: '不排班',
              ruleFrameGuid: 'no',
              type: 'no'
            }
          ]
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    /**
     * 查询数据
     */
    onQueryt() {
      console.log(this.timeValue)
      console.log(this.getDaysInMonth(this.timeValue))
      //   let date = this.getDaysInMonth(this.timeValue)
      console.log(this.dayDate)
      if (
        this.elform.userGuid == '' ||
        this.elform.userGuid == null
      ) {
        this.$message.error('请选择用户后再进行操作')
        return false
      }
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-user-rule-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            userGuid: this.elform.userGuid,
            endDate: this.dayDate[this.dayDate.length - 1],
            startDate: this.dayDate[0],
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.resDate = data.messageContent || []
          if (this.resDate.length == 0) {
            this.$message({
              message: '查询成功当月暂无排班',
              type: 'success'
            })
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },

    /**
     * 保存数据
     */
    onSubmit() {
      if (
        this.elform.userGuid == '' ||
        this.elform.userGuid == null
      ) {
        this.$message.error('请选择用户后再进行操作')
        return false
      }
      // 批量加载条
      this.loading = Loading.service({
        lock: true,
        text: '正在排班中,请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$http({
        url: this.$http.adornUrl('/attendance/attendance-user-rule-save'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            endDate: this.dayDate[this.dayDate.length - 1],
            startDate: this.dayDate[0],
            addDataList: this.resDate,
            userGuid: this.elform.userGuid,
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          // 关闭加载条
          this.loading.close()
          this.$message({
            message: '排班成功',
            type: 'success'
          })
          this.onQueryt()
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    /**
     * 日历
     */
    //处理时间
    handleTime(s) {
      return s < 10 ? '0' + s : s
    },
    // 获取考勤班次信息
    getAttendance() {
      let arr = this.elform.attendanceRuleItem.split(',')
      let ruleFrameGuid = arr[0]
      let ruleFrameName = arr[1]
      let type = arr[2]
      let ruleguid_type =
        type == 'rule' ? 'attendanceRuleGuid' : 'attendanceFrameGuid'

      let rulename_type =
        type == 'rule' ? 'attendanceRuleName' : 'attendanceFrameName'
      return {
        ruleFrameGuid,
        ruleFrameName,
        type,
        ruleguid_type,
        rulename_type
      }
    },
    // 点击
    handle() {
      if (
        this.elform.attendanceRuleItem == '' ||
        this.elform.attendanceRuleItem == null
      ) {
        this.$message.error('请选择考勤班次后再进行操作')
        return false
      }
      this.$nextTick(() => {
        let arr = JSON.parse(JSON.stringify(this.resDate))
        let is = arr.find(
          item =>
            item.attendanceDate == this.formatDate(this.timeValue, 'yyyy-MM-dd')
        )
        console.log(this.elform.attendanceRuleItem)
        const {
          ruleFrameGuid,
          ruleFrameName,
          type,
          ruleguid_type,
          rulename_type
        } = this.getAttendance()
        console.log(this.resDate)
        // 获取当前选中到考勤班次信息
        if (ruleFrameGuid == 'no') {
          if (is) {
            this.resDate = arr.filter(
              item =>
                item.attendanceDate !=
                this.formatDate(this.timeValue, 'yyyy-MM-dd')
            )
          }
        } else {
          if (is) {
            this.resDate = arr.filter(
              item =>
                item.attendanceDate !=
                this.formatDate(this.timeValue, 'yyyy-MM-dd')
            )
            this.resDate.push({
              attendanceDate: this.formatDate(this.timeValue, 'yyyy-MM-dd'),
              [ruleguid_type]: ruleFrameGuid,
              [rulename_type]: ruleFrameName,
              type,
              ruleType:2
            })
          } else {
            this.resDate.push({
              attendanceDate: this.formatDate(this.timeValue, 'yyyy-MM-dd'),
              [ruleguid_type]: ruleFrameGuid,
              [rulename_type]: ruleFrameName,
              type,
              ruleType:2
            })
          }
        }
      })
      return false
    },
    dealMyDate(v) {
      // console.log(v)
      let len = this.resDate.length
      let res = ''
      for (let i = 0; i < len; i++) {
        if (this.resDate[i].attendanceDate == v) {
          //   let type =
          //     this.resDate[i].type == 'rule'
          //       ? 'attendanceRuleName'
          //       : 'attendanceRoleName'
          //   let arr = this.resDate[i]
          //   res = arr[type]
          res = this.resDate[i]
          break
        }
      }
      // console.log(res)
      return res
    }
  }
}
</script>
<style >
/**图解 */
.building_romm_list1 {
  /* padding: 10px 10px 0 10px; */
  padding-top:10px;
}
.building_romm_list1 .shebeiColor {
  display: inline-block;
  width: 20px;
  height: 14px;
}
.building_romm_list1 span {
  margin-right: 20px;
}
.frame {
  background-color: #67c23a;
}
.rule {
  background-color: #f56c6c;
}
/**查询 */
.scheduling .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 5px;
}

.el-button-group .el-button.el-button--default.el-button--medium {
  padding: 5px 10px;
}
.scheduling {
  padding: 10px;
  user-select: none;
}
.scheduling .el-calendar-table .el-calendar-day {
  height: 60px;
}
/* 把今日样式改掉 */
.scheduling .el-backtop,
.el-calendar-table td.is-today {
  color: #303133;
}
.el-calendar-table td.is-selected {
  background: #fff;
}
/**隐藏下一月 */
.el-calendar__button-group .el-button-group > button:nth-child(1),
.el-calendar__button-group .el-button-group > button:nth-child(2),
.el-calendar__button-group .el-button-group > button:nth-child(3) {
  display: none;
}
/**日历样式 */
.el-calendar__header {
  padding: 12px 0;
}
.el-calendar__body {
  padding: 0;
}
.el-calendar-table .el-calendar-day {
  padding: 0;
}
.el-calendar-table thead th {
  background: #aaa;
}
.el-calendar-table:not(.is-range) td.next,
.el-calendar-table:not(.is-range) td.prev {
  /* background:orange; */
  cursor: not-allowed;
  pointer-events: none;
  color: #fff;
}

.el-calendar-day .isShow {
  background: #67c23a;
}
.el-calendar-day p {
  margin: 0;
  padding: 8px;
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>